package shoppingcart.fragment.utils;

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import shoppingcart.fragment.model.ShopList;

public class HttpUtils {
    private static final String TAG = "HttpUtils";
    private static final String BASE_URL = "http://47.99.134.126:28019/api/v1/shop-cart";
    private static final int CONNECT_TIMEOUT = 10000;
    private static final int READ_TIMEOUT = 10000;

    public interface OnDataReceivedListener {
        void onDataReceived(List<ShopList> shopLists);
        void onError(String errorMessage, int statusCode);
    }

    public interface OnUpdateListener {
        void onSuccess();
        void onFailure(String errorMessage);
    }

    // 获取购物车商品列表
    public static void fetchCartItems(String token, final OnDataReceivedListener listener) {
        new AsyncTask<Void, Void, Response>() {
            @Override
            protected Response doInBackground(Void... voids) {
                return makeRequest("GET", BASE_URL, token, null);
            }

            @Override
            protected void onPostExecute(Response response) {
                handleCartResponse(response, listener);
            }
        }.execute();
    }


    // 更新购物车商品数量
    public static void updateCartItemQuantity(String token, int cartItemId, int newQuantity, final OnUpdateListener listener) {
        new AsyncTask<Void, Void, Response>() {
            @Override
            protected Response doInBackground(Void... voids) {
                try {
                    JSONObject requestBody = new JSONObject();
                    requestBody.put("cartItemId", cartItemId);
                    requestBody.put("goodsCount", newQuantity);
                    return makeRequest("PUT", BASE_URL, token, requestBody.toString());
                } catch (JSONException e) {
                    Log.e(TAG, "JSON creation error", e);
                    return new Response(-1, null);
                }
            }

            @Override
            protected void onPostExecute(Response response) {
                handleUpdateResponse(response, listener);
            }
        }.execute();
    }

    // 删除购物车中的商品
    public static void deleteCartItem(String token, int cartItemId, final OnUpdateListener listener) {
        new AsyncTask<Void, Void, Response>() {
            @Override
            protected Response doInBackground(Void... voids) {
                try {
                    String url = BASE_URL + "/" + cartItemId;
                    return makeRequest("DELETE", url, token, null);
                } catch (Exception e) {
                    Log.e(TAG, "删除购物项异常", e);
                    return new Response(-1, "删除购物项异常: " + e.getMessage());
                }
            }

            @Override
            protected void onPostExecute(Response response) {
                if (response.responseCode == HttpURLConnection.HTTP_OK ||
                        response.responseCode == HttpURLConnection.HTTP_NO_CONTENT) {
                    listener.onSuccess();
                } else {
                    handleUpdateResponse(response, listener);
                }
            }
        }.execute();
    }

    // 添加商品到购物车
    public static void addToCart(String token, int goodsId, int goodsCount, final OnUpdateListener listener) {
        new AsyncTask<Void, Void, Response>() {
            @Override
            protected Response doInBackground(Void... voids) {
                try {
                    JSONObject requestBody = new JSONObject();
                    requestBody.put("goodsId", goodsId);
                    requestBody.put("goodsCount", goodsCount);
                    return makeRequest("POST", BASE_URL, token, requestBody.toString());
                } catch (JSONException e) {
                    Log.e(TAG, "JSON creation error", e);
                    return new Response(-1, null);
                }
            }

            @Override
            protected void onPostExecute(Response response) {
                handleUpdateResponse(response, listener);
            }
        }.execute();
    }

    // 通用的HTTP请求方法
    private static Response makeRequest(String method, String urlString, String token, String requestBody) {
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        OutputStream outputStream = null;

        try {
            URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod(method);
            urlConnection.setConnectTimeout(CONNECT_TIMEOUT);
            urlConnection.setReadTimeout(READ_TIMEOUT);

            // 设置请求头
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            if (token != null && !token.isEmpty()) {
                urlConnection.setRequestProperty("token", token);
            }

            // 处理POST/PUT请求体
            if (requestBody != null && (method.equals("POST") || method.equals("PUT"))) {
                urlConnection.setDoOutput(true);
                outputStream = urlConnection.getOutputStream();
                outputStream.write(requestBody.getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
            }

            urlConnection.connect();

            int responseCode = urlConnection.getResponseCode();
            InputStream inputStream = responseCode < HttpURLConnection.HTTP_BAD_REQUEST
                    ? urlConnection.getInputStream()
                    : urlConnection.getErrorStream();

            StringBuilder buffer = new StringBuilder();
            if (inputStream != null) {
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
            }

            return new Response(responseCode, buffer.toString());

        } catch (IOException e) {
            Log.e(TAG, "Network error", e);
            return new Response(-1, "网络连接失败");
        } finally {
            // 关闭所有流
            try {
                if (outputStream != null) outputStream.close();
                if (reader != null) reader.close();
                if (urlConnection != null) urlConnection.disconnect();
            } catch (IOException e) {
                Log.e(TAG, "Error closing stream", e);
            }
        }
    }

    // 处理购物车数据响应
    private static void handleCartResponse(Response response, OnDataReceivedListener listener) {
        if (response.responseCode == HttpURLConnection.HTTP_OK) {
            try {
                JSONObject jsonObject = new JSONObject(response.responseBody);
                int resultCode = jsonObject.getInt("resultCode");

                if (resultCode == 200) {
                    JSONArray dataArray = jsonObject.getJSONArray("data");
                    List<ShopList> shopLists = parseShopLists(dataArray);
                    listener.onDataReceived(shopLists);
                } else {
                    String message = jsonObject.getString("message");
                    listener.onError(message, resultCode);
                }
            } catch (JSONException e) {
                Log.e(TAG, "JSON parsing error", e);
                listener.onError("数据解析错误", -1);
            }
        } else {
            handleErrorResponse(response, listener);
        }
    }

    // 处理更新操作响应
    private static void handleUpdateResponse(Response response, OnUpdateListener listener) {
        try {
            if (response.responseBody != null && !response.responseBody.isEmpty()) {
                JSONObject jsonObject = new JSONObject(response.responseBody);
                if (jsonObject.has("message")) {
                    listener.onFailure(jsonObject.getString("message"));
                    return;
                }
            }

            if (response.responseCode == HttpURLConnection.HTTP_OK) {
                listener.onSuccess();
            } else {
                listener.onFailure("服务器错误，状态码: " + response.responseCode);
            }
        } catch (JSONException e) {
            Log.e(TAG, "JSON解析错误", e);
            listener.onFailure("数据解析错误");
        } catch (Exception e) {
            Log.e(TAG, "未知错误", e);
            listener.onFailure("未知异常: " + e.getMessage());
        }
    }

    // 解析购物车商品列表
    private static List<ShopList> parseShopLists(JSONArray dataArray) throws JSONException {
        List<ShopList> shopLists = new ArrayList<>();
        for (int i = 0; i < dataArray.length(); i++) {
            JSONObject item = dataArray.getJSONObject(i);
            shopLists.add(new ShopList(
                    item.getInt("cartItemId"),
                    item.getInt("goodsCount"),
                    item.getString("goodsCoverImg"),
                    item.getInt("goodsId"),
                    item.getString("goodsName"),
                    item.getDouble("sellingPrice")
            ));
        }
        return shopLists;
    }

    // 处理错误响应
    private static void handleErrorResponse(Response response, OnDataReceivedListener listener) {
        if (response.responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            listener.onError("登录已过期，请重新登录", response.responseCode);
        } else if (response.responseBody != null) {
            try {
                JSONObject errorObj = new JSONObject(response.responseBody);
                listener.onError(errorObj.optString("message", "请求失败"), response.responseCode);
            } catch (JSONException e) {
                listener.onError("网络错误: " + response.responseCode, response.responseCode);
            }
        } else {
            listener.onError("网络连接失败", response.responseCode);
        }
    }



    // 响应封装类
    private static class Response {
        int responseCode;
        String responseBody;

        Response(int code, String body) {
            this.responseCode = code;
            this.responseBody = body;
        }
    }


}